package com.sh.museum.ui;

import android.app.ProgressDialog;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gitonway.lee.niftymodaldialogeffects.lib.Effectstype;
import com.gitonway.lee.niftymodaldialogeffects.lib.NiftyDialogBuilder;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.sh.museum.R;
import com.sh.museum.base.BaseActivity;
import com.sh.museum.base.HD_Application;
import com.sh.museum.common.Constants;
import com.sh.museum.entities.VersionInfo;
import com.sh.museum.utils.FileUtils;
import com.sh.museum.utils.HdAppConfig;
import com.sh.museum.utils.Utils;
import com.sh.museum.view.VersionDownLoadDialog;

import java.io.File;

@ContentView(R.layout.settings)
public class Settings extends BaseActivity {
    @ViewInject(R.id.top_back_btn)
    ImageButton back;
    @ViewInject(R.id.top_title)
    TextView title;
    @ViewInject(R.id.download)
    private RelativeLayout download;
    @ViewInject(R.id.delete)
    private RelativeLayout delete;
    @ViewInject(R.id.version)
    private RelativeLayout version;

    private String language = Constants.LANGUAGE;
    private ProgressDialog dialog2;
    private static HttpUtils utils;
    private VersionDownLoadDialog dialog1;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        title.setText(R.string.settings);
    }

    @OnClick(R.id.download)
    public void download(View view) {
        if (Utils.isFileExist(Constants.BASEPATH + language + "/")) {
            final NiftyDialogBuilder builder = new NiftyDialogBuilder(Settings.this, R.style.dialog_untran);
            Effectstype effect = Effectstype.Slidetop;
            builder.setTypeface(HD_Application.TEXT_TYPE);
            builder.withTitle(getString(R.string.tips))
                    .withMessage(getString(R.string.download_existall_res))
                    .withIcon(getResources().getDrawable(R.drawable.app_icon))
                    .withDuration(700)
                    .isCancelable(false)
                    .withEffect(effect)
                    .withButton1Text(getString(R.string.confirm)).setButton1Click(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    builder.dismiss();
                    download(HdAppConfig.getAddress() + language + ".zip", Constants.BASEPATH + "temp/" + language + ".zip", Constants.BASEPATH, mHandler, false);
                }
            }).withButton2Text(getString(R.string.cancel)).setButton2Click(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    builder.dismiss();
                }
            });
            builder.show();
        } else {
            download(HdAppConfig.getAddress() + language + ".zip", Constants.BASEPATH + "temp/" + language + ".zip",Constants.BASEPATH, mHandler, false);
        }
    }

    @OnClick(R.id.version)
    public void version(View view) {
        dialog2 = new ProgressDialog(Settings.this);
        dialog2.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog2.setCancelable(false);
        dialog2.setMessage(getResources().getString(R.string.map_loading));
        dialog2.show();
        getVersion();
    }

    private void getVersion() {
        if (getConnectedType(Settings.this) == 1 && (getWifiName().contains(Constants.SSID1)||getWifiName().contains(Constants.SSID2))) {
            versionPopup1();
            dialog2.dismiss();
        } else {
            if (getConnectedType(this) != -1) {
                String deviceId = android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
                utils = new HttpUtils();
                RequestParams params = new RequestParams();
                params.addBodyParameter("appKey", "7fb674619973ebcfd81a87aae020706e");
                params.addBodyParameter("appKind", "1");
                params.addBodyParameter("deviceId", deviceId);
                params.addBodyParameter("versionCode", FileUtils.getCurrentVersion(Settings.this) + "");
                params.addBodyParameter("appSecret", "26997567cab5bea222e01b1228615c22");
                String url = "http://101.200.234.14/APPCloud/index.php?a=checkVersion";
                utils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        System.out.println("版本信息：" + responseInfo.result);
                        Gson gson = new Gson();
                        VersionInfo info = gson.fromJson(responseInfo.result, VersionInfo.class);
                        versionPopup(info);
                        dialog2.dismiss();
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        versionPopup1();
                        dialog2.dismiss();
                    }
                });
            } else {
                versionPopup1();
                dialog2.dismiss();
            }
        }

    }

    private String getWifiName() {
        String wifiName;
        WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        wifiName = wifiInfo.getSSID();
        return wifiName;
    }

    private void versionPopup1() {
        final NiftyDialogBuilder builder = new NiftyDialogBuilder(Settings.this, R.style.dialog_untran);
        Effectstype effect = Effectstype.Slidetop;
        builder.setTypeface(HD_Application.TEXT_TYPE);
        builder.withTitle(getString(R.string.settings_version))
                .withMessage(getString(R.string.current_version) + ":v" + FileUtils.getVersionName(Settings.this) + "\n"
                        + "\n" + getResources().getString(R.string.is_new_version))
                .withIcon(getResources().getDrawable(R.drawable.app_icon))
                .withDuration(700)
                .withEffect(effect)
                .withButton1Text(getString(R.string.confirm)).setButton1Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
        builder.show();
    }

    private void versionPopup(final VersionInfo info) {
        switch (info.getStatus()) {
            case "2001":
                versionPopup1();
                break;
            case "2002":
                final NiftyDialogBuilder builder = new NiftyDialogBuilder(Settings.this, R.style.dialog_untran);
                Effectstype effect = Effectstype.Slidetop;
                builder.setTypeface(HD_Application.TEXT_TYPE);
                builder.withTitle(getString(R.string.settings_version))
                        .withMessage(getString(R.string.current_version) + ":v" + FileUtils.getVersionName(Settings.this) + "\n"
                                + "\n" + getString(R.string.Latest_version) + ":" + info.getVersionInfo().getVersionName())
                        .withIcon(getResources().getDrawable(R.drawable.app_icon))
                        .withDuration(700)
                        .withEffect(effect)
                        .withButton1Text(getString(R.string.update)).setButton1Click(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog1 = new VersionDownLoadDialog(Settings.this, handler, info);
                        dialog1.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        dialog1.setIcon(R.drawable.app_icon);
                        dialog1.setTitle(getResources().getString(R.string.In_update));
                        dialog1.setCancelable(false);
                        dialog1.show();
                        builder.dismiss();
                    }
                });
                builder.show();
                break;
            case "4041":
                versionPopup1();
                break;
        }
    }

    @OnClick(R.id.delete)
    public void delete(View view) {
        final NiftyDialogBuilder builder = new NiftyDialogBuilder(Settings.this, R.style.dialog_untran);
        Effectstype effect = Effectstype.Slidetop;
        builder.isCancelableOnTouchOutside(false);
        builder.withTitle(getString(R.string.tips))
                .withMessage(getString(R.string.delete_all))
                .withIcon(getResources().getDrawable(R.drawable.app_icon))
                .withDuration(700)
                .withEffect(effect)
                .withButton1Text(getString(R.string.confirm)).setButton1Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteRes(language);
                builder.dismiss();
            }
        }).withButton2Text(getString(R.string.cancel)).setButton2Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
        builder.show();
    }

    @OnClick(R.id.top_back_btn)
    public void back(View view) {
        defaultFinish();
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    showShortToast(R.string.download_complete);
                    break;
            }
        }
    };

    private void deleteRes(final String languageStr) {
        File file = new File(Constants.BASEPATH + languageStr);
        if (!file.exists()) {
            showShortToast(R.string.setting_delete_nofile);
            return;
        }
        showProgressDialog(null, getString(R.string.setting_delete_wait), null);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Utils.deleteDir(Constants.BASEPATH + languageStr);
                dismissDialog();
                showShortToast(R.string.setting_delete_success);
            }
        }, 2000);
    }
}
